package edu.zjut.hjg.saas.web.interceptor;

import static edu.zjut.hjg.saas.web.support.SaaSConstants.SESSION_NAME_ADMIN;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import edu.zjut.hjg.saas.common.util.JsonUtil;

/**
 * 租户权限拦截器
 * 
 * @author hjg
 */
public class AdminPermissionInterceptor extends HandlerInterceptorAdapter {

    private static final String LOGIN_PAGE        = "/adminLogin.htm";
    private static final String JSON_CONTENT_TYPE = "application/json";
    private static final String JSON_ENCODE       = "UTF-8";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        if (request.getAttribute(SESSION_NAME_ADMIN) != null) {
            // 已登录
            return true;
        }
        // 未登录
        if (isAjaxRequest(request)) {
            response.setContentType(JSON_CONTENT_TYPE);
            response.setCharacterEncoding(JSON_ENCODE);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("needLogin", true);
            JsonUtil.toJSON(map, response.getOutputStream(), JSON_ENCODE);
        } else {
            response.sendRedirect(LOGIN_PAGE);
        }
        return false;
    }

    private boolean isAjaxRequest(HttpServletRequest request) {
        String uri = request.getRequestURI().toLowerCase();
        return uri.contains("ajax");
    }
}
